import { Controller, Get, Inject, LoggerService, Post, Query, Logger, ParseIntPipe, Body, Delete, Param, UseFilters, UseGuards, Req, Patch, HttpException, HttpStatus } from '@nestjs/common'
import { UserService } from './user.service'
import { getUserDto } from './dto/get-user.dto'
import { CreateUserPipe } from './pipes/create-user.pipe'
import { CreateUserDto } from './dto/create-user.dto'
import { User } from './user.entity'

import { TypeormFilter } from '../common/typeorm.filter'
import { JwtGuard } from '../guard/jwt.guard'
import { Serialize } from '../decorators/serialize.decorator'
import { PublicUserDto } from './dto/public-user.dto'
import { AdminGuard } from '../guard/admin.guard'
@Controller('user')
@UseGuards(JwtGuard)
// @UseGuards(AuthGuard('jwt'))
@UseFilters(TypeormFilter)
@Serialize(PublicUserDto)
export class UserController {
  constructor(
    private readonly userService: UserService,
    @Inject(Logger) private readonly logger: LoggerService
  ) {}

  @Get()
  @UseGuards(AdminGuard)
  getUsers(@Query() query: getUserDto) {
    // console.log(config.get('Customer')) // 使用config库读取配置文件
    return this.userService.findAll(query)
  }

  @Post()
  createUser(@Body(CreateUserPipe) dto: CreateUserDto): any {
    const user = dto as unknown as User
    return this.userService.create(user)
  }

  @Get('logsByGroup')
  async getLogsByGroup(@Query('id') id: number): Promise<any> {
    this.logger.log('getLogsByGroup')
    const res = await this.userService.findLogsByGroup(id)
    return res.map((item: any) => ({
      status: item.status,
      count: +item.count
    }))
  }
  @Get('profile')
  async getUserProfile(@Req() req): Promise<any> {
    const res = await this.userService.findProfile(req.user.userId)
    const { roles, ...ret } = res
    return { ...ret, roles: roles[0] }
  }
  @Patch('/:id')
  updateUser(@Body() dto: any, @Param('id', ParseIntPipe) id: number, @Req() req): any {
    console.log(req.user, '11')
    if (id === parseInt(req.user?.userId)) {
      return this.userService.update(id, dto)
    } else {
      throw new HttpException('用户Id不匹配', HttpStatus.BAD_REQUEST)
    }
  }
  @Delete('/:id')
  removeUser(@Param('id') id: number): any {
    return this.userService.remove(id)
  }
}
